package com.rayboo.example.thread;

public class Ticket implements Runnable {

    /**
     * 出票数
     */
    private int num = 0;

    /**
     * 剩余票数
     */
    private int count = 15;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                // 没有余票时，跳出循环
                if (count <= 0) {
                    break;
                }
                num++;
                count--;

                try {
                    // 模拟网络延时
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "抢到第" + num + "张票，剩余" + count + "张票");
            }
        }
    }

    public static void main(String[] args) {

        Ticket ticket = new Ticket();
        // 　实例化几个抢票用户
        Thread mary = new Thread(ticket, "Mary");

        Thread jack = new Thread(ticket, "Jack");

        Thread ruth = new Thread(ticket, "Rose");

        System.out.println("========出票信息========");

        mary.start();

        jack.start();

        ruth.start();

    }
}
